<template>
  <div style="padding-top: 40px">
    <div style="width: 10%;float: left;margin-top: 5px">
      <el-button size="medium" round icon="el-icon-arrow-left" @click="$router.go(-1)">返回</el-button>
    </div>
    <!--    搜索框-->
    <div style="width:90%;display:flex;justify-content: center;align-items: center;position: sticky;top: 54px;z-index: 100;margin: 0 20px 30px 0">
      <el-autocomplete ref="search"
                       v-model.trim="search.input" :fetch-suggestions="getSearchHistory" clearable
                       placeholder="请输入商品名称搜索商品"
                       style="width: 100%;border: 2px solid rgb(64,158,255);border-radius: 5px"
                       value-key="keyword"
                       @clear="clear"
                       @input="autoSearchIfInputBlank"
                       @select="searchSpu"
                       @keyup.enter.native="searchSpu">
        <el-select slot="prepend" v-model="search.selection" @change="searchSpu" style="width: 100px;line-height: inherit">
          <el-option label="商品" value="商品"></el-option>
          <el-option label="分类" value="分类"></el-option>
          <el-option label="品牌" value="品牌"></el-option>
        </el-select>
        <el-button slot="append" icon="el-icon-search" style="width: 80px"
                   @click="searchSpu"></el-button>
        <template slot-scope="{ item }">
          <div class="search-history-item" @mouseenter="search.hoveredItem = item"
               @mouseleave="search.hoveredItem = null">
            {{ item.keyword }}
            <i v-show="search.hoveredItem === item"
               class="el-icon-circle-close"
               @click.stop="removeSearchHistory(item.keyword)"/>
          </div>
        </template>
      </el-autocomplete>
    </div>
    <!--    筛选卡片-->
    <div style="display: flex;flex-wrap: wrap;align-items: flex-start">
      <!--      种类-->
      <div style="width: 100%;display: flex;align-items: flex-start;min-height: 50px;height: max-content;margin-bottom: 20px">
        <div style="font-weight: bold;width: 5%;font-size: 16px;color: #424242;margin-right: 30px">
          种类:
        </div>
        <div style="width: 95%">
          <el-radio-group size="small" v-model="search.categoryName">
            <el-radio-button style="margin-bottom: 5px" v-for="cate in cateList" :key="cate.id"
                             :label="cate.name" @click.native="filterByCategory(cate.name,$event)"></el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <!--      品牌-->
      <div style="width: 100%;display: flex;align-items: flex-start;min-height: 50px;height: max-content">
        <div style="font-weight: bold;width: 5%;font-size: 16px;color: #424242;margin-right: 30px">
          品牌:
        </div>
        <div style="width: 95%;display: flex;align-items: flex-start;flex-wrap: wrap">
          <el-radio-group size="small" v-model="search.brandName">
            <el-radio-button style="margin-bottom: 5px;" v-for="brand in brandList" :key="brand.id"
                             :label="brand.name" @click.native="filterByBrand(brand.name,$event)"></el-radio-button>
          </el-radio-group>
        </div>
      </div>
    </div>
<!--    排序-->
    <div style="display: flex;justify-content: flex-end;align-items: center">
      <el-button-group>
        <el-button icon="el-icon-s-grid" size="small" type="primary" @click="()=>{search.sortType=0;searchSpu()}">综合</el-button>
        <el-button size="small" type="primary" @click="sortBySales">
          <i v-show="search.sortType!==1&&search.sortType!==2" class="el-icon-sort"></i>
          <i v-show="search.sortType===1" class="el-icon-sort-up"></i>
          <i v-show="search.sortType===2" class="el-icon-sort-down"></i>
          销量
        </el-button>
        <el-button size="small" type="primary" @click="sortByPrice">
          <i v-show="search.sortType!==3&&search.sortType!==4" class="el-icon-sort"></i>
          <i v-show="search.sortType===3" class="el-icon-sort-up"></i>
          <i v-show="search.sortType===4" class="el-icon-sort-down"></i>
          价格</el-button>
      </el-button-group>
    </div>
    <!--      搜索商品，下拉加载更多-->
    <el-row :gutter="10" style="margin-top: 10px">
      <el-card shadow="never">
        <el-row :gutter="10">
          <el-col v-for="spu in spuList" :key="spu.id" :span="5">
            <SpuCard :spu="spu"/>
          </el-col>
        </el-row>
        <el-empty v-show="!this.spuList.length" description="很抱歉，没有找到相关鞋子"></el-empty>
      </el-card>
    </el-row>
  </div>
</template>
<script>
import {getBrandList, getCateList, getSpuListFront} from "@/api/goods";
import {getSearchHistory, getUser, pushSearchHistory, removeSingleSearchHistory} from "@/utils/storage";
import SpuCard from "@/components/common/SpuCard.vue";

export default {
  name: "Search",
  components: {SpuCard},
  data() {
    return {
      search: {
        input: '',
        name: '',
        brandName: '',
        categoryName: '',
        selection: '商品',
        //排序类型, 0代表默认,1、2代表按销量升降序,3、4代表按价格升降序
        sortType:0,
        hoveredItem: null,
      },
      cateList: [],
      brandList: [],
      spuList: [],
      user: {},
      page: {
        pageNum: 1,
        pageSize: 8,
        total: 0
      }
    }
  },
  created() {
    this.user = getUser()
    this.search.input = this.$route.params.input
    this.search.selection = this.$route.params.selection?this.$route.params.selection:'商品'
    this.load()
  },
  methods: {
    sortBySales(){
      if(this.search.sortType===2) {
        this.search.sortType=0
      }
      else if(this.search.sortType===1){
        this.search.sortType=2
      }else{
        this.search.sortType=1
      }
      this.page.pageNum = 1
      this.loadSpuList()
    },
    sortByPrice(){
      if(this.search.sortType===4) {
        this.search.sortType=0
      }
      else if(this.search.sortType===3){
        this.search.sortType=4
      }else{
        this.search.sortType=3
      }
      this.page.pageNum = 1
      this.loadSpuList()
    },
    //label是点击的标签名，而categoryName是之前选中的标签名
    filterByCategory(label,event){
      //使用原生点击事件会执行两次该方法
      if(event.target.tagName !== 'INPUT') return
      //点击自己，取消选中
      if(label===this.search.categoryName){
        this.search.categoryName=''
      }else {
        this.search.categoryName=label
      }
      this.page.pageNum = 1
      this.loadSpuList()
    },
    filterByBrand(label,event){
      if(event.target.tagName !== 'INPUT') return
      if(label===this.search.brandName){
        this.search.brandName=''
      }else {
        this.search.brandName=label
      }
      this.page.pageNum = 1
      this.loadSpuList()
    },
    clear() {
      //由于vue数据异步更新，所以在清空input后，需要nextTick再执行聚焦操作从而展开完整的历史记录
      this.$nextTick(() => {
        this.$refs.search.getInput().blur()
        this.$refs.search.focus()
      })
    },
    autoSearchIfInputBlank() {
      if (this.search.input === '') {
        this.searchSpu()
      }
    },
    getSearchHistory(keyword, callback) {
      callback(getSearchHistory(keyword))
    },
    saveSearchHistory() {
      pushSearchHistory({keyword: this.search.input, selection: this.search.selection})
    },
    removeSearchHistory(keyword) {
      removeSingleSearchHistory(keyword)
      this.$refs.search.suggestions = getSearchHistory()
    },
    setSearchInput() {
      this.search.name = ''
      this.search.brandName = ''
      this.search.categoryName = ''
      if (this.search.selection === '商品') {
        this.search.name = this.search.input
      } else if (this.search.selection === '品牌') {
        this.search.brandName = this.search.input
      } else if (this.search.selection === '分类') {
        this.search.categoryName = this.search.input
      }
    },
    searchSpu() {
      this.setSearchInput()
      //如果输入框有值
      if (this.search.input !== '') {
        console.log('save')
        //保存历史记录
        this.saveSearchHistory()
      }
      //每次搜索都需要重置pageNum
      this.page.pageNum = 1
      this.loadSpuList()
    },
    loadSpuList() {
      getSpuListFront(this.search, this.page).then(res => {
        if (res.code === '0') {
          this.spuList = res.data.records
          this.page.total = res.data.total
        }
      })
    },
    load() {
      this.searchSpu()
      getCateList().then(res => {
        if (res.code === '0') {
          this.cateList = res.data.map(category => {
            return {
              id: category.id,
              name: category.name
            }
          })
        }
      })
      getBrandList().then(res => {
        if (res.code === '0') {
          this.brandList = res.data.map(brand => {
            return {
              id: brand.id,
              name: brand.name
            }
          })
        }
      })
    },
    scrollToBottom() {
      if (this.spuList.length < this.page.total) {
        this.page.pageNum++
        getSpuListFront(this.search, this.page).then(res => {
          if (res.code === '0') {
            this.spuList = this.spuList.concat(res.data.records)
          }
        })
      }
    }
  },
};
</script>

<style scoped>


.search-history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px;
  cursor: pointer;
}

.el-col-5 {
  width: 20%;
}
</style>
